package com.desay.pangoo.itmt.controller.rag;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.desay.pangoo.common.lite.lang.web.CommonResponse;
import com.desay.pangoo.itmt.entity.rag.RagRelationTreeEntity;
import com.desay.pangoo.itmt.repository.rag.RagRelationTreeEntityRepository;
import com.desay.pangoo.itmt.repository.spec.ExpandCriteria;
import com.desay.pangoo.itmt.repository.spec.Restrictions;
import com.desay.pangoo.itmt.service.LLMService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;

/**
 * AI 智能问答
 * 
 * @author uids1175
 */
@RestController
@Api(tags = "RAG 技术树")
@RequestMapping(value = "/rag/tree")
@Validated
@Log4j2
public class TechRelateTreeController {

	@Autowired
	private RagRelationTreeEntityRepository ragRelationTreeEntityRepository;
	@Autowired
	private LLMService llmService;

	@GetMapping
	@ApiOperation(value = "获取技术树信息", notes = "")
	public ResponseEntity<Object> treeRelated(@RequestParam(value = "id", required = false) Long id) {
		ExpandCriteria<RagRelationTreeEntity> c = new ExpandCriteria<>();
		if (Objects.isNull(id)) {
			c.add(Restrictions.isNull("parent"));
		} else {
			c.add(Restrictions.eq("parent.id", id, true));
		}
		List<RagRelationTreeEntity> list = ragRelationTreeEntityRepository.findAll(c);
		return new ResponseEntity<>(CommonResponse.success(list), HttpStatus.OK);
	}

	@GetMapping("/{id}")
	@ApiOperation(value = "叶子节点关联相关提案", notes = "ID为最底层叶子节点ID")
	public ResponseEntity<Object> treeRelatedTech(@PathVariable("id") Long id) {
		RagRelationTreeEntity entity = ragRelationTreeEntityRepository.findById(id).orElse(null);
		JSONObject requestObject = new JSONObject();
		JSONObject data = new JSONObject();
		data.put("classification", entity.getParent());
		data.put("sub_technology", entity);
		requestObject.put("json_data", data);
		return new ResponseEntity<>(CommonResponse.success(llmService.treeRelated(requestObject)), HttpStatus.OK);
	}

	@PostMapping("/project/chat")
	@ApiOperation(value = "提案对应字段的优化", notes = "")
	public ResponseEntity<Object> projectChart(@RequestBody JSONObject data) {
		return new ResponseEntity<>(CommonResponse.success(llmService.projectChart(data)), HttpStatus.OK);
	}

	@GetMapping("/loadtech")
	@ApiOperation(value = "加载技术树", notes = "")
	public ResponseEntity<Object> loadTreeTech() throws FileNotFoundException {
		File folder = new File("D:\\uidq1163\\Downloads\\itmt_technology_tree\\json_3");
		File[] files = folder.listFiles();
		// 遍历文件夹下的所有文件
		for (File file : files) {
			String fileName = FileUtil.getPrefix(file.getName());
			log.info("{},{}", file.getAbsolutePath(), fileName);
			RagRelationTreeEntity parent = ragRelationTreeEntityRepository.findByKeyNameAndParentIsNull(fileName);

			List<RagRelationTreeEntity> parents = ragRelationTreeEntityRepository.findByParent(parent);
			File[] subFiles = file.listFiles();
			for (File subfile : subFiles) {
				if (subfile.isFile()) {
					// 读取 JSON 文件
					// json文件对象转换成json
					cn.hutool.json.JSONObject jsonObject = JSONUtil.readJSONObject(subfile, Charset.forName("GBK"));
					String subFileName = FileUtil.getPrefix(subfile.getName());
					log.info("{},{}", subfile.getAbsolutePath(), subFileName);
					try {
						RagRelationTreeEntity subParent = parents.stream()
								.filter((item) -> item.getKeyName().equalsIgnoreCase(subFileName)).findFirst()
								.orElseThrow(() -> new Exception("not found"));
						// 遍历 JSON 对象的每个属性
						saveData(jsonObject, subParent);
					} catch (Exception e) {
						e.printStackTrace();
						log.error("{},{}", subfile.getAbsolutePath(), subFileName);
					}
				}

			}
		}

		return new ResponseEntity<>(CommonResponse.success(), HttpStatus.OK);
	}

	@GetMapping("/load")
	@ApiOperation(value = "加载技术树", notes = "")
	public ResponseEntity<Object> loadTree() throws FileNotFoundException {
		File folder = new File("D:\\uidq1163\\Downloads\\itmt_technology_tree\\json_2");
		File[] files = folder.listFiles();
		// 遍历文件夹下的所有文件
		for (File file : files) {
			if (file.isFile()) {
				// 读取 JSON 文件
				// json文件对象转换成json
				cn.hutool.json.JSONObject jsonObject = JSONUtil.readJSONObject(file, Charset.forName("GBK"));
				String fileName = FileUtil.getPrefix(file.getName());
				RagRelationTreeEntity parent = ragRelationTreeEntityRepository.findByKeyName(fileName);
				// 遍历 JSON 对象的每个属性
				saveData(jsonObject, parent);
			}
		}

		return new ResponseEntity<>(CommonResponse.success(), HttpStatus.OK);
	}

	@GetMapping("/loadgroup")
	@ApiOperation(value = "加载技术树", notes = "")
	public ResponseEntity<Object> loadTreeGroup() throws FileNotFoundException {

		// 读取 JSON 文件
		// json文件对象转换成json
		cn.hutool.json.JSONObject jsonObject = JSONUtil.readJSONObject(
				new File("D:\\uidq1163\\Downloads\\itmt_technology_tree\\itmt_group.json"), Charset.forName("UTF-8"));

		// 遍历 JSON 对象的每个属性
		saveData(jsonObject, null);
		return new ResponseEntity<>(CommonResponse.success(), HttpStatus.OK);
	}

	private void saveData(cn.hutool.json.JSONObject jsonObject, RagRelationTreeEntity parent) {
		// 遍历 JSON 对象的每个属性
		for (String key : jsonObject.keySet()) {
			cn.hutool.json.JSONObject item = jsonObject.getJSONObject(key);
			String nameEn = item.getStr("name_en");
			String nameZh = item.getStr("name_zh");
			String keywordsZh = item.getStr("keywords_zh");
			String keywordsEn = item.getStr("keywords_en");
			String definition = item.getStr("definition");
			String scope = item.getStr("scope");
			RagRelationTreeEntity entity = new RagRelationTreeEntity();
			entity.setName_en(nameEn);
			entity.setName_zh(nameZh);
			entity.setKeywords_zh(keywordsZh);
			entity.setKeywords_en(keywordsEn);
			entity.setDefinition(definition);
			entity.setScope(scope);
			entity.setKeyName(key);
			if (parent != null) {
				entity.setParent(parent);
			} else {
				entity.setParent(ragRelationTreeEntityRepository.findByKeyName(key));
			}
			ragRelationTreeEntityRepository.save(entity);
		}
	}
}
